package com.service.impl;

import com.dao.UserDao;
import com.pojo.ResponsePojo;
import com.pojo.User;
import com.service.UserService;
import com.util.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Autowired//自动注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public ResponsePojo exist(String username) {
        User user = userDao.findByUsername(username);
        //用户名没有查到，可用
        if(user == null) {
            return ResponsePojo.SUCCESS;
        }
        return ResponsePojo.FAIL;
    }

    @Override
    public ResponsePojo regist(User user) {
        //生成一个随机的激活码
        String code = UUID.randomUUID().toString().replaceAll("-", "");
        //将激活码添加到user对象
        user.setCode(code);
        int i = userDao.add(user);
        if(i > 0){
            //发送邮件
            MailUtils.sendMail(user.getEmail(), "<a href='http://localhost:8080/book/user/active?code="+ code +"'>请点击此处进行激活</a>", "邮箱激活");
            return ResponsePojo.SUCCESS;
        }
        return ResponsePojo.FAIL;
    }

    @Override
    public ResponsePojo active(String code) {
        User user = userDao.findByCode(code);
        if(user == null) {
            //没有找到
            return ResponsePojo.SUCCESS;
        } else {
            //修改状态码
            userDao.updateById(user.getId());
            return ResponsePojo.FAIL;
        }
    }

    @Override
    public User login(String username, String password) {
        User user = userDao.findByUsernameAndPassword(username, password);
        return user;
    }

    @Override
    public ResponsePojo updatePwd(String password, int id) {
        int i = userDao.updatePwd(password, id);
        if(i > 0){
            return ResponsePojo.SUCCESS;
        }
        return ResponsePojo.FAIL;
    }

    @Override
    public ResponsePojo findAll() {
        return new ResponsePojo<>(200, "查询成功" ,userDao.findAll());
    }
}
